import os
from typing import Optional
from PyQt5.QtWidgets import QSystemTrayIcon
from .logger import logger

def _show_notification(title: str, message: str, icon: QSystemTrayIcon.MessageIcon = QSystemTrayIcon.Information):
    """显示系统通知"""
    try:
        from PyQt5.QtWidgets import QApplication
        if QApplication.instance():
            for widget in QApplication.topLevelWidgets():
                if hasattr(widget, 'tray_icon'):
                    widget.tray_icon.showMessage(title, message, icon, 3000)
                    return
    except Exception as e:
        logger.error(f"显示通知失败: {str(e)}")

def notify_recording_started():
    """通知录制开始"""
    _show_notification(
        "录制开始",
        "屏幕录制已开始",
        QSystemTrayIcon.Information
    )

def notify_recording_paused():
    """通知录制暂停"""
    _show_notification(
        "录制暂停",
        "屏幕录制已暂停",
        QSystemTrayIcon.Information
    )

def notify_recording_resumed():
    """通知录制恢复"""
    _show_notification(
        "录制恢复",
        "屏幕录制已恢复",
        QSystemTrayIcon.Information
    )

def notify_recording_stopped(output_path: Optional[str] = None):
    """通知录制停止"""
    message = "屏幕录制已停止"
    if output_path:
        message += f"\n保存至: {output_path}"
    _show_notification(
        "录制停止",
        message,
        QSystemTrayIcon.Information
    )

def notify_recording_failed(error: str):
    """通知录制失败"""
    _show_notification(
        "录制失败",
        f"录制出现错误: {error}",
        QSystemTrayIcon.Critical
    )

def notify_publish_started(platform: str):
    """通知发布开始"""
    _show_notification(
        "开始发布",
        f"正在发布到{platform}...",
        QSystemTrayIcon.Information
    )

def notify_publish_success(platform: str):
    """通知发布成功"""
    _show_notification(
        "发布成功",
        f"成功发布到{platform}",
        QSystemTrayIcon.Information
    )

def notify_publish_failed(platform: str, error: str):
    """通知发布失败"""
    _show_notification(
        "发布失败",
        f"发布到{platform}失败: {error}",
        QSystemTrayIcon.Critical
    )

def notify_error(title: str, message: str):
    """通知错误"""
    _show_notification(
        title,
        message,
        QSystemTrayIcon.Critical
    )
